package com.c.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.c.entity.Permission;
import com.c.entity.Role;
import com.c.entity.User;
import com.c.mapper.PermissionMapper;
import com.c.mapper.RoleMapper;
import com.c.mapper.UserMapper;
import com.c.service.UserService;
import com.c.utils.MessageConstant;
import com.c.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author wangxiangli
 * @create 2022-12-25-12:30
 */
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();

    //根据用户名查询数据库获取用户信息和关联的角色信息，同时需要查询角色关联的权限信息
    @Override
    public User findByUsername(String username) {
        QueryWrapper<User> wrapper=new QueryWrapper();
        wrapper.eq("username",username);
        User user = baseMapper.selectOne(wrapper);
        if(user==null){
            return null;
        }
        Integer userId=user.getId();
        Set<Role> roleSet = roleMapper.findByUserId(userId);
        if(roleSet!=null){
            for(Role role:roleSet){
                Integer roleId = role.getId();
                Set<Permission> permissions = permissionMapper.findByRoleId(roleId);
                if (permissions != null) {
                    role.setPermissions(permissions);//让角色关联权限
                }
            }
            user.setRoles(roleSet);
        }
        return user;
    }

    @Override
    public Result add(User user, Integer[] roleIds) {
        //先判断用户名是否存在，确保用户名的唯一性（t_user）
        //long count = userDao.findExist(user.getUsername());
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("username",user.getUsername());
        Long count = baseMapper.selectCount(wrapper);
        if (count > 0) {
            return new Result(false, "该用户名已经存在,无法创建");
        } else {
//            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            String password = bCryptPasswordEncoder.encode(user.getPassword());
            user.setPassword(password);
            //新增用户，操作t_user表
             baseMapper.insert(user);
            //设置用户和角色的多对多的关联关系，操作t_user_role表
            Integer userId = user.getId();
            this.setCheckUserAndCheckRole(userId, roleIds);
            return new Result(true, MessageConstant.ADD_USER_SUCCESS);

    }
}



    /**
     * 建立用户和角色的多对多关系
     *
     * @param userId
     * @param roleIds
     */
    private void setCheckUserAndCheckRole(Integer userId, Integer[] roleIds) {
        if (roleIds != null && roleIds.length > 0) {
            Map<String, Integer> map = null;
            for (Integer roleId : roleIds) {
                map = new HashMap<>();
                map.put("userId", userId);
                map.put("roleId", roleId);
                baseMapper.setCheckUserAndCheckRole(map);
            }
        }
    }

    /**
     * 回显编辑数据
     * @param id
     * @return
     */
    @Override
    public Map findByIdWithAllRole(Integer id) {
        //根据用户id查询 用户的基本信息
        User formData = baseMapper.selectById(id);
        //查询所有的角色信息
        List<Role> tableData = roleMapper.selectList(null);
        //根据用户的id 查询用户对应的角色id
        List<Integer> roleIds = roleMapper.findRoleById(id);
        Map<String, Object> map = new HashMap<>();
        map.put("formData", formData);
        map.put("tableData", tableData);
        map.put("roleIds", roleIds);
        return map;
    }
    /**
     * 编辑用户信息
     *
     * @param user
     * @param roleIds
     */
    @Override
    public void edit(User user, Integer[] roleIds) {
        //修改用户表基本信息，操作t_user表
        baseMapper.updateById(user);
        //清理当前用户关联的角色，操作中间关系表 t_user_role 表
        baseMapper.deleteAssociation(user.getId());
        //重新建立当前用户和角色的关联关系，操作 t_user_role 表
        Integer userId = user.getId();
        this.setCheckUserAndCheckRole(userId, roleIds);
    }
    /**
     * 删除用户信息
     *
     * @param id
     * @return
     */
    @Override
    public Result deleteById(Integer id) {
        //判断删除的用户是否存在管理员角色
        Set<Role> roles = roleMapper.findByUserId(id);//使用set去重
        if (roles.size() > 0) {
            for (Role role : roles) {
                if (role.getKeyword().equals("ROLE_ADMIN")) {
                    return new Result(false, "该用户为系统管理员权限不可删除");
                }
            }
        }
        //删除用户和角色的关联表(t_user_role)的数据,根据用户id进行删除
        baseMapper.deleteAssociation(id);
        //删除用户
        baseMapper.deleteById(id);
        return new Result(true, MessageConstant.DELETE_USER_SUCCESS);
    }
    /**
     * 获取用户名称
     *
     * @param id
     * @return
     */
    @Override
    public User showUsername(Integer id) {
        return baseMapper.showUsername(id);
    }


    /**
     * 更改批量用户密码
     * @param map
     */
    @Override
    public void changePassword(Map map) {
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        User user = new User();
        user.setUsername(username);
        String BCpassword = bCryptPasswordEncoder.encode(password);
        user.setPassword(BCpassword);
        baseMapper.changePassword(user);
    }
    /**
     * 更改登录用户密码
     *
     * @param map
     */
    @Override
    public Result modifyPassword(Map map) {
        String oldPassword = (String) map.get("oldPassword");
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        //1.比对原密码是否一样
        String passwordByUser = baseMapper.findPasswordByUser(user);
        //对passwordByUser进行解密比对
        boolean matches = bCryptPasswordEncoder.matches(oldPassword, passwordByUser);
        if (!matches) {
            return new Result(false, "原密码输入错误");
        }
        //对密码进行加密
        password = bCryptPasswordEncoder.encode(password);
        user.setPassword(password);
        //修改密码
        baseMapper.changePassword(user);
        return new Result(true, MessageConstant.CHANEG_PASSWORD_USER_SUCCESS);
    }

    @Override
    public void hello() {
        baseMapper.deleteById(18);
    }

    @Override
    public List<User> getUserByRemark() {
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("remark","健康管理师");
        List<User> users = baseMapper.selectList(wrapper);
        return users;
    }


}
